var tokenClient = {};
dojo.require("dojox.cometd");
var cometd = dojox.cometd;
var connection = {};

tokenClient.Object = function(hostUrl, tokenInstance) {
  this.REST_Path = hostUrl + "synchronizer/token";
  this.Repository_Path = hostUrl + "synchronizer/";       
  this.contextPath = "/eva";

  this.instanceName = tokenInstance;
  //this.subscription = null;
  //Subscribe cometD to predefined instance
  this.subscription2Display = null;
  
  this._myNmbr = '';
  this._countDown = 0;
  this._hasHelloAction = 0;
  this._keepCountingFlag = true;  
  //DEL this._startCountDownFrom = 0;  
};

tokenClient.Object.prototype.doInit = function() {
  if (this.subscription2Display) {
      cometd.unsubscribe(this.subscription2Display);
  }
  this.subscription2Display = cometd.subscribe(this.instanceName, token.whenDisplayPublishes);
    //Geppetizanje
  this._odaziv = dojo.byId('odaziv');
  //#Try 1
  this._odaziv.addEventListener("click", executeAction, false);  //in geppetoExtension.js
  this._odaziv.addEventListener("mouseover", highlight_target, false); //in geppetoExtension.js
  this._odaziv.addEventListener("mouseout", unhighlight_target, false); //in geppetoExtension.js
  
  zdravo = dojo.byId('zdravo');
  zdravo.addEventListener("click", executeAction, false);  //in geppetoExtension.js
  zdravo.addEventListener("mouseover", highlight_target, false); //in geppetoExtension.js
  zdravo.addEventListener("mouseout", unhighlight_target, false); //in geppetoExtension.js
  
  // var this._akcijaOdlaska = dojo.byId('leavingAction');
  // this._akcijaOdlaska.addEventListener("click", set_action, false);  //in geppetoExtension.js
  // this._akcijaOdlaska.addEventListener("mouseover", highlight_target, false); //in geppetoExtension.js
  // this._akcijaOdlaska.addEventListener("mouseout", unhighlight_target, false); //in geppetoExtension.js

  //TODO not crucial for the first run
  //this.subscription2MyWaitTimer = cometd.subscribe(this.instanceName + myUserIdCookie +'-timer', this.whenDisplayPublishes);
  return;
}
  
tokenClient.Object.prototype.reset = function(){
	this._myNmbr = '';
	dojo.byId('myNmbr').innerHTML = "-";
	dojo.byId('selectedWaiting').selected = 'Zauvijek';
	// pobrisi Geppeto akcije programirane u gumbima
	dojo.byId('zdravo').value = "Odazovi se!";	
	if (this._odaziv.value != "Izabran!")
		this._odaziv.value = "Nije izabran";
	else
		this._hasHelloAction = 1;
	//This is for remembering or uncomment for reseting 
	//Geppetizing values in geppetoExtension.js
	// this._odaziv.setAttribute("module_id", ""); 
	// this._odaziv.setAttribute("xpath", "");						
	// this._odaziv.setAttribute("g_name", "");
	// this._odaziv.setAttribute("g_element", "");
	this._odaziv.setAttribute("style", "width:100px");
	return;
}

tokenClient.Object.prototype.initialGUI_state = function() {
	dojo.byId('dovidjenja').disabled = true;
	dojo.byId('zdravo').disabled = true;
	dojo.byId('odaziv').disabled = false;
	dojo.byId('dosta').disabled = true;
	dojo.byId('uzmi').disabled = false;
    dojo.byId('propustam').disabled = false;
	dojo.byId('itIsYourTurn').style.display = "none"; dojo.byId('pickWaitingTime').style.display = "inline";
	dojo.byId('pickLeavingAction').style.display = "none"; dojo.byId('enough-LeaveNow').style.display = "inline";
	dojo.byId('countDown').style.display = "none"; dojo.byId('pickComingAction').style.display = "inline";
	return;
}

tokenClient.Object.prototype.clearAction = function() {
    odaziv = document.getElementById('odaziv');
    odaziv.setAttribute("module_id", ""); 
    odaziv.setAttribute("xpath", "");						
    odaziv.setAttribute("g_name", "");
    odaziv.setAttribute("g_element", "");
    odaziv.setAttribute("style", "width:100px");
    odaziv.setAttribute("title", "");
    odaziv.value = "Nije izabran";

    zdravo = document.getElementById('zdravo');
    zdravo.setAttribute("module_id", ""); 
    zdravo.setAttribute("xpath", "");						
    zdravo.setAttribute("g_name", "");
    zdravo.setAttribute("g_element", "");
    zdravo.setAttribute("style", "width:100px");
    zdravo.setAttribute("title", "");
    zdravo.value = "Odazovi se!";

	token._hasHelloAction = 0;
    document.getElementById('clearAction').style.display = "none";
    document.getElementById('clearAction2').style.display = "none";
}

tokenClient.Object.prototype.whenDisplayPublishes = function(message){
	//DEL dojo.byId('debug_console').innerHTML =  message.data.msg;
	//DEBUG Message is JSONized by cometd-dojo library i guess	
	var msg = message.data.msg;
	//True, but msg is nog JSONized, darn... took me 3h of sleep
	msg = eval("(" + msg + ")");

	//NOT INFORMING USER when BYE returns> "Calling a new number failed"
	if (msg == "Exception"){
		dojo.byId('message').innerHTML = "Experiencing difficulties at server";
		return;
	}
	var zaslon =dojo.byId('zaslon');
	if (msg.description == "nothing_to_display") {
		//Leave the last nmbr on screen, and wait for it even after timer 
		// until someone else shows up
		//zaslon.innerHTML = " - - -";
		return;
	}
	var callingNmbr = msg.modification.callingNmbr;
	if (callingNmbr == null)
		return;		
	zaslon.innerHTML = callingNmbr;
	token._keepCountingFlag = false;
	token._countDown = msg.modification.waiting_in_sec;	
	token.numberEqualsToMine();	
};

tokenClient.Object.prototype.numberEqualsToMine = function(){
	callingNmbr = dojo.byId('zaslon').innerHTML - 0;
	this._myNmbr = dojo.byId('myNmbr').innerHTML - 0;
	//LEARN Cudno, this._myNumber i this._countDown su ostali na pocetnoj vrijednosti koja je u konstruktoru
	// Nisu se prenjeli iz funkcija pa zato citam iz DOM elementa
	//Za _myNmber to mogu iz DOMa, ali za _countDown ne mogu
	//Bit ce da je to zato sto sam u ajax callback fjama koristio this._myNmbr, a ne token._myNmbr
	//Ajmo provjerit
	
	//Missed my call, number called is greater than mine
	if(callingNmbr > this._myNmbr) {
	//When debugging this._myNmbr was "" and callingNmbr was "2"
	// But zaslon is not defined in ftion, how can this be
		//TODO enable take new nmbr, disable other actions
		//It is assumed this number has left the system
		//Needs to take a new number		
		token.initialGUI_state();
		return;
	}

	//Nubmer is less than mine
	//TODO FIX 
	//It is possible that at this time, REST did not return result, and _myNmbr is undefined or stale
	//That is why I check when REST returns
	if (this._myNmbr != callingNmbr)
		return;

	//Number equals to mine
	//No matter who called this ftion, need to schedule timer if numbers match
	if (this._countDown == null)
		return;
	
	//Schedule timer to change 
	if (this._countDown > 0){
		token._keepCountingFlag = true;
		//DEL examp: window.setTimeout("blueText.style.display='block';",3000,"JavaScript");
		setTimeout("token.decreaseCountDown();", 1000);
        dojo.byId('countDownValue').innerHTML = this._countDown;
		dojo.byId('countDownDescription').style.display = "inline";
		dojo.byId('awaitingNextConsumer').style.display = "none";
		//MJERENJE
		//display contdown div
		// ali cijeli ovaj if trebam stavit negdje gore
		//TBC
	}
		
	//Display other divs
	dojo.byId('itIsYourTurn').style.display = "inline"; dojo.byId('pickWaitingTime').style.display = "none";
	dojo.byId('pickLeavingAction').style.display = "none"; dojo.byId('enough-LeaveNow').style.display = "none";
	if (this._hasHelloAction == 0){	
		dojo.byId('countDown').style.display = "inline"; dojo.byId('pickComingAction').style.display = "none";
		dojo.byId('zdravo').disabled = false;
		dojo.byId('dovidjenja').disabled = true;
	} 
	else {
		//TODO! Okini onaj gumb koji je isprogramiran
		//On bi trebao okiniti hello(), ali samo jednom
		//i kliknut tamo gdje je korisnik isprogramirao				
		//executeAction(document.getElementById(SET_ACTION));
		executeAction(document.getElementById('odaziv'));
		token.hello(0);
		dojo.byId('odaziv').disabled = false;
		dojo.byId('dovidjenja').disabled = true;
	}
	return
};

tokenClient.Object.prototype.decreaseCountDown = function(){
	this._countDown--;
	dojo.byId('countDownValue').innerHTML = this._countDown;
	if (this._countDown > 0 && this._keepCountingFlag){
		setTimeout("token.decreaseCountDown();", 1000);
		return;
	}
	//if (this._countDown == 0) or less
	//After not showing, it is assumed that that one has left
	//But if no one else showed up and took a number, 
	// the number is valid even after time out
	// So, I need to inform this 
	if (this._keepCountingFlag){
		dojo.byId('countDownDescription').style.display = "none";
		dojo.byId('awaitingNextConsumer').style.display = "inline";	
	}
	return;
};

tokenClient.Object.prototype.choosePoslovnica = function() {
  //In example application.js they check and unsubscribe their previous subscription
  
  //Only predefined instance supported currently  
  //this.instanceName = tokenClient.INSTANCE;
  
  alert('This action is not supported.');
  
  //This part is what should be supported
  // if (this.subscription) {
      // cometd.unsubscribe(this.subscription);
  // }
  // var txBox = document.getElementById(idToGetInstanceName);
  // this.instanceName = txBox.value;
  // this.subscription = cometd.subscribe(this.instanceName, this.whenSubscribed);
  // txBox.value = "";
  return;
};

tokenClient.Object.prototype.selectedWaiting = function() {
	//TODO not crucial for the first run
	//var sel = dojo.byId('selectedWaiting').selected
	//if (sel == ...)
	return;
}

tokenClient.Object.prototype.leave = function() {
	//Reset and show initial divs
	this.reset()
	this.initialGUI_state();
	//dojo.byId('message').innerHTML = "Odbacili ste broj, odustali od cekanja.";
	return;
}


tokenClient.Object.prototype.takeNmbr = function() {
  dojo.byId('uzmi').disabled = true;
  if (this.instanceName == '')
    return "Failed: ticket office not selected";
  var message = dojo.byId('message');
  var time = new Date();
  var xhrArgs = {
	url: this.REST_Path,
	handleAs: "text",
	preventCache: true,
	content: {
		"name": this.instanceName,
		"operation": "takeNmbr",
		"mechanism": "token",
		"user": "fakeCookie",
		"timeStamp": time.getTime()
	},
	load: token.takeNmbrCallback, 
	error: function(error) {
		message.innerHTML = "An unexpected error occurred: " + error;
	}
  }
  //Call the asynchronous xhrGet
  //var deferred = dojo.xhrPost(xhrArgs);
  this.sendAjax(xhrArgs);
  return;
};

tokenClient.Object.prototype.takeNmbrCallback = function(resp) {
		//gadgets.io.makeRequest returns object as parametar to callback ftion
		//To retrieve data from that object use object.data
		//My data is JSON, so I need to JSONize it
		
		//Eneble it, so it stays enabled if something brakes
		dojo.byId('uzmi').disabled = false;
		data = resp.data;
		if ( data.indexOf("{") != 0 || data == "Geting a number failed" || data == "Putting a number failed" 
		    || data == "Exception" || data == "Failed" ) {
			message = dojo.byId('message');
			message.innerHTML = data;
			return;
		}		
		var res = eval('(' + resp.data + ')');
		var nmbr = res.modification.tokenNmbr
		if (nmbr == null) {
			return;
		}		
		token._myNmbr = nmbr;	
		token._keepCountingFlag = true;
		dojo.byId("myNmbr").innerHTML = token._myNmbr;
		dojo.byId('message').innerHTML = "Izdan vam je broj. Odazovite se kada prozovemo vas broj.";
		//Disable takeNmbr, enable other GUI actions
		dojo.byId('dovidjenja').disabled = true;
		dojo.byId('uzmi').disabled = true;
		dojo.byId('zdravo').disabled = false;
		dojo.byId('odaziv').disabled = false;
		dojo.byId('dosta').disabled = false;
		token.numberEqualsToMine(); //LEARN Zasto ovdje mora token, a _myNmbr moze sa this
		return;	
};

tokenClient.Object.prototype.hello = function(/*int*/ hasHelloAction) {
  var odaziv = dojo.byId('odaziv');
  if (this.instanceName == '')
    return "Failed: ticket office not selected";
	//If his number is called, send hello to server
  if (dojo.byId('zaslon').innerHTML != this._myNmbr)
	return;
  if (hasHelloAction && odaziv.value != "Izabran!")
     return; //Blokira javljanje na salter, ako nije prozvan 
  this._hasHelloAction = hasHelloAction;
  var message = dojo.byId('message');
  var time = new Date();
  var xhrArgs = {
            url: this.REST_Path,
            handleAs: "text",
            preventCache: true,
            content: {
                "name": this.instanceName,
                "operation": "hello",
				"nmbr":this._myNmbr,
                "mechanism": "token",
				"timeStamp": time.getTime()
            },
            load: function(resp) {
				//TODO provjeri da li Geppeto 2 puta pozove, jednom ja kliknem, drugi put Geppeto
				// tu ce mi mozda jos trebati ovaj hasHelloAction
				// za brisanje, resetiranje te akcije koja je dodana event listenerima
				// a koristim ga u numberEqualsToMine za prikaz jednog ili drugog div
				// kad se javi poklapanje 
                data = resp.data;
				if (data != "Hello")
					return;					
				//Disable countdown
				token._keepCountingFlag = false;
				message.innerHTML = "Odazvali ste se na vrijeme. Izvolite...";
				dojo.byId('dovidjenja').disabled = false;
				dojo.byId('odaziv').disabled = true; //Geppeto is higlighting as well
				dojo.byId('zdravo').disabled = true; 
                dojo.byId('propustam').disabled = true;
				return;
            },
            error: function(error) {
                message.innerHTML = "An unexpected error occurred: " + error;
            }
    }

  //Call the asynchronous xhrGet
  //var deferred = dojo.xhrPost(xhrArgs);
  this.sendAjax(xhrArgs);
  return;
}

tokenClient.Object.prototype.bye = function() {
  if (this.instanceName == '')
    return "Failed: ticket office not selected";
  var message = dojo.byId('message');
  var time = new Date();
  var xhrArgs = {
            url: this.REST_Path,
            handleAs: "text",
            preventCache: true,
            content: {
                "name": this.instanceName,
                "operation": "bye",
                "mechanism": "token",
				"timeStamp": time.getTime()
            },
            load: function(resp) {
				data = resp.data
				if (data != "Bye")
					return;
				message.innerHTML = "Dovidjenja.";
				//is leaving...
				token.leave();
				return;
            },
            error: function(error) {
                message.innerHTML = "An unexpected error occurred: " + error;
            }
    }

  //Call the asynchronous xhrGet
  //var deferred = dojo.xhrPost(xhrArgs);
  this.sendAjax(xhrArgs);
  return;
}

tokenClient.Object.prototype.getDisplNmbr = function() {
  if (this.instanceName == '')
    return "Failed: ticket office not selected";
  var message = dojo.byId('message');
  var time = new Date();
  var xhrArgs = {
            url: this.REST_Path,
            handleAs: "text",
            preventCache: true,
            content: {
                "name": this.instanceName,
                "operation": "getCount",
                "mechanism": "token",
				"timeStamp": time.getTime()
            },
            load: function(resp) {
				data = resp.data
				if (data=="Failed")
					return;
				var res = eval('(' + resp.data + ')');
				var nmbr = res.mechanism.counter;
				if (nmbr == null) {
					return;
				}	
				var zaslon =dojo.byId('zaslon');
				zaslon.innerHTML = nmbr;
				return;
            },
            error: function(error) {
                message.innerHTML = "An unexpected error occurred: " + error;
            }
    }
  //Call the asynchronous xhrGet
  //var deferred = dojo.xhrPost(xhrArgs);
  this.sendAjax(xhrArgs);
  return;
}

tokenClient.Object.prototype.sendAjax = function(xhrArgs){
  if(gadgets.io !=null){
	var params = {};
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
	var url =  xhrArgs.url +"?";
	i = 0;
	for(var key in xhrArgs.content) {
		if (i) url += '&';
		url += key + "=" + xhrArgs.content[key];
		i++;
	}
	gadgets.io.makeRequest(url, xhrArgs.load, params);
  }
}
